//
//  JKSettingViewController.swift
//  ZhiHuDaily-Swift
//
//  Created by albert on 2018/3/13.
//  Copyright © 2018年 安永博. All rights reserved.
//

import UIKit
import Kingfisher

class JKSettingViewController: UITableViewController {
    
    
    /** 自动离线下载开关 */
    @IBOutlet weak var autoDownloadSwitch: UISwitch!
    
    /** 摇一摇夜间模式开关 */
    @IBOutlet weak var shakeToChangeSkinSwitch: UISwitch!
    
    /** 移动网络不下载图片开关 */
    @IBOutlet weak var noImageWithouWifiSwitch: UISwitch!
    
    /** 关闭阅读位置提示开关 */
    @IBOutlet weak var readPositionNoticeOffSwitch: UISwitch!
    
    /** 推送消息开关 */
    @IBOutlet weak var pushMessageSwitch: UISwitch!
    
    /** 用户头像 */
    @IBOutlet weak var iconImageView: UIImageView!
    
    /** 用户名 */
    @IBOutlet weak var userNameLabel: UILabel!
    
    /** 缓存大小label */
    @IBOutlet weak var cacheSizeLabel: UILabel!
    
    /** 旋转菊花 */
    @IBOutlet weak var indicatorView: UIActivityIndicatorView!
    
    /** 导航条背景view */
    lazy var navBgView: UIView = {
        
        let navBgView = UIView(frame: CGRect(x: 0, y: 0, width: JKScreenW, height: JKNavBarHeight))
        navBgView.isUserInteractionEnabled = true
        navBgView.backgroundColor = JKMainColor
        tableView.addSubview(navBgView)
        
        return navBgView
    }()
    
    /** 返回按钮 */
    lazy var navBackButton: UIButton = {
        
        let button = UIButton(type: UIButtonType.custom)
        
        button.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        
        button.setTitleColor(UIColor.white, for: UIControlState.normal)
        button.setTitleColor(UIColor.lightGray, for: UIControlState.highlighted)
        button.setImage(UIImage(named: "Back_White"), for: UIControlState.normal)
        button.setImage(UIImage(named: "Back"), for: UIControlState.highlighted)
        //        button.backgroundColor = UIColor.red
        button.addTarget(self, action: #selector(navBackButtonClick), for: UIControlEvents.touchUpInside)
        
        // 让button里面的内容移到最左边
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignment.left
        // 设置button的内容偏移，可以与上面的Alignment配合，也可以直接设置偏移量更大些，比如-10改为-80
        //button.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0)//想让导航条的按钮距离边上更近些，可以用这个
        //        button.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0)
        button.imageEdgeInsets = UIEdgeInsets(top: 0, left: -8, bottom: 0, right: 0)
        //        button.backgroundColor = [UIColor redColor]
        // contentMode一般用来设置imageView，设置button没有用
        // button.contentMode = UIViewContentModeLeft
        
        // 让button的大小适配里面的内容
        //        [button sizeToFit]
        button.height = 44
        button.width = 44
        
        // 设置返回按钮为自定义是没有反应的
        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: button)
        
        return button
    }()
    
    /** 控制器当前皮肤模式 */
    var vcSkinModel: String = ""
    
    /** 当前属性列表保存的皮肤模式 */
    var currentSkinModel: String {
        
        return UserDefaults.standard.string(forKey: JKCurrentSkinModelKey) ?? JKDaySkinModelValue
    }
    
    // MARK:- 生命周期方法
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        NotificationCenter.default.addObserver(self, selector: #selector(updateSkin), name: NSNotification.Name(JKSkinModelDidChangedNotification), object: nil)
        
        updateUserIconAndName()
        tableView.reloadData()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        updateSkin()
        tableView.bringSubview(toFront: navBgView)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: JKSkinModelDidChangedNotification), object: nil)
    }
    
    // MARK: - 初始化

    override func viewDidLoad() {
        super.viewDidLoad()
        
        automaticallyAdjustsScrollViewInsets = false
        
        tableView.jk_adapt_iOS_11_scrollView()
        
        tableView.contentInset = UIEdgeInsetsMake(JKNavBarHeight - 10, 0, JKCurrentHomeIndicatorHeight, 0)
        
        if #available(iOS 11.0, *) {
            
        } else {
            
            tableView.scrollIndicatorInsets = UIEdgeInsetsMake(JKNavBarHeight, 0, JKCurrentHomeIndicatorHeight, 0)
        }
        
        tableView.backgroundColor = JKGlobalBgColor
        
        let _ = navBackButton
        
        navigationItem.title = "设置"
        
        setupSwitches()
        updateUserIconAndName()
        
        //获取软件配置文件Info.plist
        let info = Bundle.main.infoDictionary//[NSBundle mainBundle].infoDictionary
        
        //版本号的key
        let versionKey = "CFBundleShortVersionString"
        
        //获取当前软件的版本号
        let currentVersion = info![versionKey]
        
        let tipLabel = UILabel(frame: CGRectMake(0, 0, JKScreenW, 44))
        
        tipLabel.text = String(format: "v%@", currentVersion as! CVarArg)
        tipLabel.textAlignment = NSTextAlignment.center
        tipLabel.font = UIFont.systemFont(ofSize: 12)
        tipLabel.textColor = JKColor(186, 186, 186)
        self.tableView.tableFooterView = tipLabel
        
        self.indicatorView.startAnimating()
        
        // 获取缓存大小
        KingfisherManager.shared.cache.calculateDiskCacheSize(completion: { (size) in
            
            let MB = CGFloat(size) / 1024.0 / 1024.0
            
            self.cacheSizeLabel.text = String(format: "(已使用%.2fMB)", MB)
            self.cacheSizeLabel.isHidden = false
            self.indicatorView.stopAnimating()
        })
    }
    
    /** updateUserIconAndName */
    private func updateUserIconAndName() {
        
        self.userNameLabel.text = UserDefaults.standard.string(forKey: JKUserNameKey) ?? "未登录"
        
        if !JKAccountManager.shared.isLogin {
            
            self.iconImageView.image = UIImage(named: "Setting_Avatar")?.jk_circleImage()
            
            return
        }
        
        let imgPath = ((NSHomeDirectory() as NSString).appendingPathComponent("Documents") as NSString).appendingPathComponent("userIcon.png")
        
        var img = UIImage(contentsOfFile: imgPath)
        
        if (img == nil) {
            
            img = UIImage(named: "myIcon")?.jk_circleImage()
        }
        
        self.iconImageView.image = img
    }
    
    /** 初始化所有开关 */
    private func setupSwitches() {
        
        self.autoDownloadSwitch.onTintColor = JKMainColor
        self.shakeToChangeSkinSwitch.onTintColor = self.autoDownloadSwitch.onTintColor
        self.noImageWithouWifiSwitch.onTintColor = self.autoDownloadSwitch.onTintColor
        self.readPositionNoticeOffSwitch.onTintColor = self.autoDownloadSwitch.onTintColor
        self.pushMessageSwitch.onTintColor = self.autoDownloadSwitch.onTintColor
        
        self.autoDownloadSwitch.isOn = UserDefaults.standard.bool(forKey: JKAutoDownloadKey)
        self.shakeToChangeSkinSwitch.isOn = UserDefaults.standard.bool(forKey: JKIsShakeCanChangeSkinKey)
        self.readPositionNoticeOffSwitch.isOn = UserDefaults.standard.bool(forKey: JKReadPositionNoticeOffKey)
        
        self.autoDownloadSwitch.isEnabled = false
        self.noImageWithouWifiSwitch.isEnabled = false
        self.pushMessageSwitch.isEnabled = false
    }
    
    // MARK: - 点击事件
    
    @objc func navBackButtonClick() {
        
        let mainNav = navigationController as! JKMainNavigationController
        
        if mainNav.showLeftVcBlock != nil {
            
            mainNav.showLeftVcBlock!()
        }
    }
    
    // 自动离线下载开关
    @IBAction func autoDownloadSwitchClick(sender: UISwitch) {
        
        UserDefaults.standard.set(sender.isOn, forKey: JKAutoDownloadKey)
        UserDefaults.standard.synchronize()
    }
    
    // 摇一摇夜间模式
    @IBAction func shakeToChangeSkinSwitchClick(sender: UISwitch) {
        
        UserDefaults.standard.set(sender.isOn, forKey: JKIsShakeCanChangeSkinKey)
        UserDefaults.standard.synchronize()
    }

    /** 阅读位置提示开关 */
    @IBAction func readPositionNoticeOffSwitch(sender: UISwitch) {
        
        UserDefaults.standard.set(sender.isOn, forKey: JKReadPositionNoticeOffKey)
        UserDefaults.standard.synchronize()
    }
    
    /** 递归查找cell */
    private func searchCellInView(superView: UIView, bgColor: UIColor) {
        
        for subView in superView.subviews {
            
            if subView is UITableViewCell {
                
                (subView as! UITableViewCell).backgroundColor = bgColor
            }
            
            searchCellInView(superView: subView, bgColor: bgColor)
        }
    }
    
    /** 递归查找label */
    private func searchLabelInView(superView: UIView, textColor: UIColor) {
        
        for subView in superView.subviews {
            
            if subView is UILabel {
                
                if (subView as! UILabel).text == "设置" ||
                    (subView as! UILabel).text == "设置" ||
                    subView == self.tableView.tableFooterView { continue }
                
                (subView as! UILabel).textColor = textColor
            }
            
            searchLabelInView(superView: subView, textColor: textColor)
        }
    }
            
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

extension JKSettingViewController{
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = super.tableView(tableView, cellForRowAt: indexPath)
        
        if self.vcSkinModel == JKNightSkinModelValue { // 夜间模式
            
            cell.backgroundColor = JKNightSkinBgColor
            searchLabelInView(superView: cell, textColor: JKSameRGBColor(160))
            
        }else{ // 日间模式
            
            cell.backgroundColor = UIColor.white
            searchLabelInView(superView: cell, textColor: UIColor.black)
        }
        
        return cell
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        if indexPath.section == 0 { // 个人信息
            
            if !JKAccountManager.shared.isLogin {
                
                JKLoginViewController.show()
                
                return
            }
            
            let vc = JKMeViewController()
            vc.isSettingIn = true
            navigationController?.pushViewController(vc, animated: true)
            
        }else if  indexPath.section == 5 { // 清除缓存
            
            JKProgressHUD.showWithStatus(status: "正在清理...", isAllowUserAction: false)
            
            KingfisherManager.shared.cache.clearDiskCache(completion: {
                
                self.cacheSizeLabel.isHidden = true
                JKProgressHUD.showSuccess(withStatus: "清理缓存成功！")
            })
            
        }else if  indexPath.section == 7 { // 查看启动图
            
            JKImageBrowserView.showWith(image: UIImage(named: "launch_img_bak.jpg"))
            JKProgressHUD.showInfo(withStatus: "啊哦，启动图api又更新了，等我查到之后再更新吧。")
        }
    }
}

extension JKSettingViewController{
    
    override func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        self.navBgView.y = -JKNavBarHeight + 10 + (scrollView.contentOffset.y + JKNavBarHeight - 10)
    }
}

extension JKSettingViewController: JKUpdateSkinProtocol {
    
    func updateSkin() {
        
        if vcSkinModel == currentSkinModel {
            return
        }
        
        self.vcSkinModel = self.currentSkinModel
        
        if self.vcSkinModel == JKNightSkinModelValue { // 夜间模式
            
            self.view.backgroundColor = JKNightSkinBgColor
            self.navBgView.backgroundColor = JKNightSkinNavColor
            self.navigationController?.navigationBar.tintColor = JKSameRGBColor(186)
            self.navBackButton.setTitleColor(UIColor.red, for: UIControlState.normal)
            
            self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor : JKSameRGBColor(186), NSAttributedStringKey.font: UIFont.systemFont(ofSize: 18)]
            
//            searchCellInView(superView: tableView, bgColor: JKNightSkinBgColor)
//            searchLabelInView(superView: tableView, textColor: JKSameRGBColor(160))
            
        }else{ // 日间模式
            
            self.view.backgroundColor = JKGlobalBgColor
            self.navBgView.backgroundColor = JKMainColor
            self.navigationController?.navigationBar.tintColor = UIColor.white
            self.navBackButton.setTitleColor(UIColor.white, for: UIControlState.normal)
            
            self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor : UIColor.white, NSAttributedStringKey.font: UIFont.systemFont(ofSize: 18)]
            
//            searchCellInView(superView: tableView, bgColor: UIColor.white)
//            searchLabelInView(superView: tableView, textColor: UIColor.black)
        }
        
        tableView.reloadData()
    }
}
